﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using XCI.Helper;
using XCI.Windows;

namespace XCI.Forms
{
    public partial class FrmWidgetItemsManager : BaseForm
    {
        private WidgetObject _widgetObject;
        private List<WidgetCaptionAttribute> providerAttrs;
        public FrmWidgetItemsManager(WidgetObject widgetObject)
        {
            InitializeComponent();
            _widgetObject = widgetObject;
        }

        private void FrmWidgetItemsManager_Load(object sender, EventArgs e)
        {
            providerAttrs = WinFormHelper.GetComponentCaptionProvider<WidgetCaptionAttribute>(p => ObjectHelper.ValidInterfaceClass(p, false, typeof(IWidget)));
            checkedListBoxControl1.Items.BeginUpdate();
            foreach (var provider in providerAttrs)
            {
                var has = _widgetObject.WidgetData.Any(p => p == provider.Code);
                checkedListBoxControl1.Items.Add(provider.Code, provider.Caption, has ? CheckState.Checked : CheckState.Unchecked, true);
            }
            checkedListBoxControl1.Items.EndUpdate();
        }

        private async void BtnSave_Click(object sender, EventArgs e)
        {
            var items = new List<string>();
            foreach (CheckedListBoxItem item in checkedListBoxControl1.CheckedItems)
            {
                items.Add(item.Value.ToString());
            }
            _widgetObject.SetItems(items);
            await _widgetObject.SaveItemsAsync();
            DialogOk();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            DialogCancel();
        }
    }
}